package com.zmx.patientend.fragment.patient;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.CaseManagementAdapter;
import com.zmx.patientend.adapter.MyRecipeAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.ArchivesDetails;
import com.zmx.patientend.pojo.CaseManagement;
import com.zmx.patientend.pojo.MyRecipe;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.activity.CArchivesDetailsActivity;
import com.zmx.patientend.view.activity.CaseManagementActivity;
import com.zmx.patientend.view.activity.PrescriptionMouldDetailsActivity;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 程序猿：胖胖祥
 * 时 间：2020/9/19  15:22
 * 功 能：病例管理
 */
public class CaseManagementFragment extends Fragment {


    private RecyclerView reView;
    private SmartRefreshLayout refreshLayout;
    private CaseManagementAdapter adapter;
    private List<ArchivesDetails> lists;
    private View mEmptyLayout;

    private String patient_id;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_case_management, container, false);


        Bundle bundle =this.getArguments();//得到从Activity传来的数据
        patient_id = null;
        if(bundle!=null){
            patient_id = bundle.getString("patient_id");
        }

        mEmptyLayout = view.findViewById(R.id.empty);
        reView = view.findViewById(R.id.reView);
        reView.setLayoutManager(new LinearLayoutManager(CaseManagementFragment.this.getContext()));
        adapter = new CaseManagementAdapter(CaseManagementFragment.this.getActivity());
        reView.setAdapter(adapter);
        lists = new ArrayList<>();
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent(CaseManagementFragment.this.getContext(), CArchivesDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("pomr_id",lists.get(listPosition).getId()+"");
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

        // 开启自动加载功能
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {

            getPomrList();

        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            refreshLayout.finishLoadMore(true);

        });

        //触发自动刷新
        refreshLayout.autoRefresh();


        return view;

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:

                    try {

                        lists.clear();

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Gson gson = new Gson();
                        if (object.getInt("code") == 1){

                            JSONArray array = object.getJSONArray("data");

                            for (int i =0 ;i<array.length();i++){

                                ArchivesDetails myRecipe = gson.fromJson(array.get(i).toString(),ArchivesDetails.class);
                                lists.add(myRecipe);

                            }

                            adapter.setListAndNotifyDataSetChanged(lists);

                        }
                        if (lists.size() > 0) {

                            mEmptyLayout.setVisibility(View.GONE);

                        } else {

                            mEmptyLayout.setVisibility(View.VISIBLE);

                        }

                        refreshLayout.finishRefresh(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };

    public void getPomrList() {

        List<String> ls = new ArrayList<>();
        ls.add(patient_id);

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(CaseManagementFragment.this.getActivity()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(CaseManagementFragment.this.getActivity()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getPomrList");
        params.put("data[patient_id]", patient_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.pomr/entry", params, handler, 1, 404);

    }


    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();

        requestparams.append(MySharedPreferences.getInstance(CaseManagementFragment.this.getActivity()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(CaseManagementFragment.this.getActivity()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(CaseManagementFragment.this.getActivity()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();
    }


}